﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.IO;
using IBS;


namespace HQCSupplierCodeLoader
{
    public partial class Service1 : ServiceBase
    {
        private Timer timer = null;

        public Service1()
        {
            InitializeComponent();
            try
            {
                if (!EventLog.SourceExists(this.ServiceName + "_log"))
                    EventLog.CreateEventSource(this.ServiceName, this.ServiceName + "_log");
            }
            catch { }
            serviceLog.Source = this.ServiceName + "_log";
            serviceLog.Log = this.ServiceName + "_log";
        }

        protected override void OnStart(string[] args)
        {
            serviceLog.WriteEntry(this.ServiceName + " запущен");
            Properties.Settings.Default.Reload();
            var ExecuteTimes = Properties.Settings.Default.ExecuteTimes;
            if (Properties.Settings.Default.ExecuteImmediately)
                ExecuteTimes.Add(DateTime.Now.AddMinutes(1).ToString("HH:mm"));

            timer = new Timer();
            timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
            timer.Interval = TimerUtil.GetNewTimerInterval(ExecuteTimes);
            timer.Enabled = true;
        }

        protected override void OnStop()
        {
            serviceLog.WriteEntry(this.ServiceName + " остановлен");
            timer.Stop();
            timer.Close();
        }

        /// <summary>
        /// При срабатывании таймера
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void OnElapsedTime(object source, ElapsedEventArgs e)
        {
            // Останавливаем таймей и стартуем выполнение выгрузки
            timer.Stop();
            Process();
            // Интервал таймера
            Properties.Settings.Default.Reload();
            timer.Interval = TimerUtil.GetNewTimerInterval(Properties.Settings.Default.ExecuteTimes);
            timer.Start();
        }

        private void Process()
        {
            try
            {
                string path = Properties.Settings.Default.Path;
                string IBSConnectionString = Properties.Settings.Default.IBSConnectionString;
                
                var ibs = new IBS.IbsDataContext(IBSConnectionString);
                var files = Directory.GetFiles(path, "Supplier_Code*.txt", SearchOption.TopDirectoryOnly);
                
                foreach (var file in files)
                {
                    try
                    {
                        FileInfo fi = new FileInfo(file);
                        var parser = new IBS.Parser(fi.FullName);
                        var result = parser.parseFile();
                        
                        ibs.DeleteHQCSupplierCode(result.FirstOrDefault().SITECODE);
                        foreach (HQCSUPPLIER_CODE line in result)
                        {
                            try
                            {
                                ibs.SaveHQCSupplierCode(line);
                            }
                            catch (Exception ex)
                            { }
                        }
                    }
                    catch (Exception ex)
                    { }

                }

            }
            catch (Exception ex)
            {
            }
        }
    }
}
